package com.java.service.impl;

import com.java.bean.Express;
import com.java.dao.BaseExpressDao;
import com.java.dao.impl.ExpressDaoMysql;
import com.java.exception.DuplicateCodeException;
import com.java.exception.DuplicateNumberException;
import com.java.service.ExpressService;
import com.java.util.RandomCodeUtil;
import com.java.util.SMSUtil;

import java.util.List;
import java.util.Map;

/**
 * @ClassName ExpressServiceImpl
 * @Description Service实现类
 * @Author 0715-YuHao
 * @Date 2020/9/10 22:12
 * @Version 1.0
 */
public class ExpressServiceImpl implements ExpressService {
    private BaseExpressDao dao = new ExpressDaoMysql();

    @Override
    public List<Map<String, Integer>> console() {
        return dao.console();
    }

    @Override
    public List<Express> findAll(boolean limit, int... args) {
        return dao.findAll(limit, args);
    }

    @Override
    public Express findByNumber(String number) {
        return dao.findByNumber(number);
    }

    @Override
    public Express findByCode(String code) {
        return dao.findByCode(code);
    }

    @Override
    public List<Express> findByUserPhone(String userPhone) {
        return dao.findByUserPhone(userPhone);
    }

    @Override
    public List<Express> findByUserPhoneAndStatus(String userPhone, int status) {
        return dao.findByUserPhoneAndStatus(userPhone, status);
    }

    @Override
    public List<Express> findBySysPhone(String sysPhone) {
        return dao.findBySysPhone(sysPhone);
    }

    @Override
    public boolean insert(Express e) throws DuplicateNumberException {
        try {
            //1.生成取件码
            e.setCode(RandomCodeUtil.getCode());
            //2.录入快递
            boolean insert = dao.insert(e);
            if (insert) {
                //3.录入成功，发送短信
                //SMSUtil.send(e.getUserPhone(), e.getCode());
            }
            return insert;
        } catch (DuplicateCodeException duplicateCodeException) {
            //3.取件码重复时,递归重新录入
            insert(e);
        }
        return false;
    }

    @Override
    public boolean update(int id, Express newExpress) throws DuplicateNumberException {
        if (newExpress.getUserPhone() != null) {
            dao.delete(id);
            return insert(newExpress);
        }else {
            boolean update = dao.update(id, newExpress);
            Express e = dao.findByNumber(newExpress.getNumber());
            if (newExpress.getStatus() == 1) {
                updateStatus(e.getCode());
            }
            return update;
        }
    }

    @Override
    public boolean updateStatus(String code) {
        return dao.updateStatus(code);
    }

    @Override
    public boolean delete(int id) {
        return dao.delete(id);
    }
}
